#include "circlequeue.hpp"
#include "Task.hpp"
#include <time.h>

class Info
{
public:
    Info(CircleQueue<Task> *cq,const string& name)
    :_cq(cq),
    _name(name)
    {
        ;
    }

    ~Info()
    {
        ;
    }
public:
    CircleQueue<Task> *_cq;
    string _name;
};

void *Consumer(void *args)
{
    Info *info = static_cast<Info *>(args);
    CircleQueue<Task> *cq = info->_cq;

    while (1)
    {
        // sleep(1);
        Task task = cq->pop();
        task.run();
        cout << info->_name << "消费了一个任务" << task.GetResult() <<endl;
    }
}

void *Productor(void *args)
{
    Info *info = static_cast<Info *>(args);
    CircleQueue<Task> *cq = info->_cq;

    while (1)
    {
        int data1 = rand() % 11 + 1;
        int data2 = rand() % 3;
        char op = oper[rand() % 5];

        Task task(data1,data2,op);

        cq->push(task);

        cout << info->_name << "生产了一个任务" << task.GetQuestion() << endl;
    }
}

int main()
{
    srand(time(nullptr));

    CircleQueue<Task> *cq = new CircleQueue<Task>();

    pthread_t c[3];
    for(int i=0;i<3;i++)
    {
        string name = "Consumer-" + to_string(i+1);
        Info* info = new Info(cq,name);

        pthread_create(c+i, nullptr, Consumer, info);

    }

    pthread_t p[3];
    for(int i=0;i<3;i++)
    {
        string name = "Productor-" + to_string(i+1);
        Info* info = new Info(cq,name);
        pthread_create(p+i, nullptr, Productor, info);
    }

    for(int i=0;i<3;i++)
    {
        pthread_join(c[i], nullptr);
    }

    for(int i=0;i<3;i++)
    {
        pthread_join(p[i], nullptr);
    }

    return 0;
}